package com.oceansoft.mobile.econsole.modules.weixin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.common.constant.ConfigInfo;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.MD5Util;
import com.oceansoft.mobile.econsole.common.util.encrypt.DesAPPUtils;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.complaint.entity.ComplaintReport;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.DriverLicenseSearchCondition;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.InQueryServiceInfo;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.WechatMessage;
import com.oceansoft.mobile.econsole.modules.jlapi.service.IJlApiService;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMemberMange;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.modules.weixin.config.Constant;
import com.oceansoft.mobile.econsole.modules.weixin.entity.*;
import com.oceansoft.mobile.econsole.modules.weixin.entity.Dictionary;
import com.oceansoft.mobile.econsole.modules.weixin.persistence.WeixinQueryMapper;
import com.oceansoft.mobile.econsole.modules.weixin.service.WeixinQueryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * Created by zeng on 2016/8/8.
 */
@Service
@Transactional
public class WeixinQueryServiceImpl implements WeixinQueryService {

    @Resource
    private WeixinQueryMapper weixinQueryMapper;

    @Resource
    protected ConfigInfo configInfo;

    @Resource
    private IJlApiService jlApiService;

    @Resource
    private IWtMemberService wtMemberService;

    /**
     * 电子警察分布
     */
    public List<CluesModel> getXsjblx (String type){
        return weixinQueryMapper.getXsjblx(type);
    }

    /**
     * 电子警察分布
     */
    public List<Dzjcfb> getDzjcfbList (){
        return weixinQueryMapper.getDzjcfbList();
    }

    /**
     * 违法代码
     */
    public Wfdm getWfdm(String dm) {
        return weixinQueryMapper.getWfdm(dm);
    }

    /**
     * 处罚机关代码
     */
    public Cfjgdm getCfjgdm(String dm) {
        return weixinQueryMapper.getCfjgdm(dm);
    }

    /**
     * 保安员考试成绩
     */
    public Baykscj getBaykscj(String zkzh) {
        return weixinQueryMapper.getBaykscj(zkzh);
    }

    /**
     * 户籍分局
     */
    public Hjfj getFj(String pcs, String jd, String sq) {
        return weixinQueryMapper.getFj(pcs,jd,sq);
    }

    /**
     * 绑定驾驶证
     * @return
     */
    @Override
    public Result bdjsz(HttpServletRequest request){
        String guid = request.getParameter("guid").toString();
        String mz = request.getParameter("mz").toString();//驾驶证编号
        String hyzk = request.getParameter("hyzk").toString();//档案编号

       WtMember wtMember= wtMemberService.getWtMemberByUserGuid(guid);
        if (com.oceansoft.mobile.econsole.common.util.StringUtils.isBlank(mz)) {
            return new Result(Result.FAILURE,"请输入驾驶证号码!");
        }
        if (com.oceansoft.mobile.econsole.common.util.StringUtils.isBlank(hyzk)) {
            return new Result(Result.FAILURE,"请输入档案编号!");
        }

        String myjszbh="";
        boolean b=false;
        try {
         myjszbh=DesAPPUtils.decrypt(wtMember.getUserCode());
            if(!(myjszbh.equals(mz)))
            {
                return new Result(Result.FAILURE,"与本人身份证不相同");
            }
            DriverLicenseSearchCondition driverLicenseSearchCondition = new DriverLicenseSearchCondition();
            driverLicenseSearchCondition.setDabh(hyzk);
            driverLicenseSearchCondition.setJtglywdxsfzhm(mz);

            String command = JSON.toJSONString(driverLicenseSearchCondition);
            InQueryServiceInfo inQueryServiceInfo
                    = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                    , InQueryServiceInfo.API_010, InQueryServiceInfo.API_ASYNC_Y, command
                    , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

          b=  jlApiService.doExecute(inQueryServiceInfo);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(false==b){
            return new Result(Result.FAILURE,"驾驶证信息输入错误，无法绑定");
        }

        //驾驶证信息属实，进入绑定
        try {
            mz=DesAPPUtils.encrypt(mz);
            weixinQueryMapper.bdjsz(guid, mz, hyzk);
        }catch ( Exception e){
            return new Result(Result.SUCC,"绑定失败");
        }
        return new Result(Result.SUCC,"绑定成功");
    }

    /**
     * 绑定车辆
     * @return
     */
    @Override
    public Result bdcl() {
        return null;
    }
    /**
     * 得到受理编号
     */
    public String getSlbh(String type) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        String time=sdf.format(new Date());
//        String time = weixinQueryMapper.getTime();
        String slbh = "";
        String top = "";

        if(type.equals(Constant.TSJY_JZXX)){
            top = "JX";
        }else if(type.equals(Constant.TSJY_JFJJ)){
            top = "JY";
        }else if(type.equals(Constant.WXJB_XSJB)){
            top = "XB";
        }else if(type.equals(Constant.WXJB_CQJFYHBZ)){
            top = "CB";
        }else if(type.equals(Constant.WXJB_GJCZXT)){
            top = "GB";
        }else if(type.equals(Constant.KCLP)){
            top = "KP";
        }

        if(type.equals(Constant.TSJY_JZXX) || type.equals(Constant.TSJY_JFJJ)){
            String oldSlbh = weixinQueryMapper.getTsjySlbh(type);

            if(null == oldSlbh){
                slbh = top + time + "00001";
            }else{
                String nf = oldSlbh.substring(2,6);
                String year = time.substring(0,4);

                if(year.equals(nf)){
                    String bh = oldSlbh.substring(10,14);

                    if(bh.startsWith("0000")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 2){
                            slbh = top + time + "000" + num;
                        }else{
                            slbh = top + time + "0000" + num;
                        }
                    }else if(bh.startsWith("000")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 3){
                            slbh = top + time + "00" + num;
                        }else{
                            slbh = top + time + "000" + num;
                        }
                    }else if(bh.startsWith("00")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 4){
                            slbh = top + time + "0" + num;
                        }else{
                            slbh = top + time + "00" + num;
                        }
                    }else if(bh.startsWith("0")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 5){
                            slbh = top + time + num;
                        }else{
                            slbh = top + time + "0" + num;
                        }
                    }else{
                        String num = String.valueOf((Integer.valueOf(bh) + 1));
                        slbh = top + time + num;
                    }
                }else{
                    slbh = top + time + "00001";
                }

            }
        }else if(type.equals(Constant.WXJB_XSJB) || type.equals(Constant.WXJB_CQJFYHBZ) || type.equals(Constant.WXJB_GJCZXT)){
            if(type.equals(Constant.WXJB_XSJB)){
                type = Constant.WXJB_XSJB_TRUE;
            }else if(type.equals(Constant.WXJB_CQJFYHBZ)){
                type = Constant.WXJB_CQJFYHBZ_TRUE;
            }else if(type.equals(Constant.WXJB_GJCZXT)){
                type = Constant.WXJB_GJCZXT_TRUE;
            }

            String oldSlbh = weixinQueryMapper.getWxjbSlbh(type);

            if(null == oldSlbh){
                slbh = top + time + "00001";
            }else{
                String year = time.substring(0,4);
                String nf = oldSlbh.substring(2,6);

                if(year.equals(nf)){
                    String bh = oldSlbh.substring(10,15);

                    if(bh.startsWith("0000")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 2){
                            slbh = top + time + "000" + num;
                        }else{
                            slbh = top + time + "0000" + num;
                        }
                    }else if(bh.startsWith("000")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 3){
                            slbh = top + time + "00" + num;
                        }else{
                            slbh = top + time + "000" + num;
                        }
                    }else if(bh.startsWith("00")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 4){
                            slbh = top + time + "0" + num;
                        }else{
                            slbh = top + time + "00" + num;
                        }
                    }else if(bh.startsWith("0")){
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if(num.length() == 5){
                            slbh = top + time + num;
                        }else{
                            slbh = top + time + "0" + num;
                        }
                    }else{
                        String num = String.valueOf((Integer.valueOf(bh) + 1));
                        slbh = top + time + num;
                    }
                }else{
                    slbh = top + time + "00001";
                }

            }
        }else if(type.equals(Constant.KCLP)) {

            String oldSlbh = weixinQueryMapper.getKclpSlbh();

            if (null == oldSlbh) {
                slbh = top + time + "00001";
            } else {
                String year = time.substring(0, 4);
                String nf = oldSlbh.substring(2, 6);

                if (year.equals(nf)) {
                    String bh = oldSlbh.substring(10, 15);

                    if (bh.startsWith("0000")) {
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if (num.length() == 2) {
                            slbh = top + time + "000" + num;
                        } else {
                            slbh = top + time + "0000" + num;
                        }
                    } else if (bh.startsWith("000")) {
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if (num.length() == 3) {
                            slbh = top + time + "00" + num;
                        } else {
                            slbh = top + time + "000" + num;
                        }
                    } else if (bh.startsWith("00")) {
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if (num.length() == 4) {
                            slbh = top + time + "0" + num;
                        } else {
                            slbh = top + time + "00" + num;
                        }
                    } else if (bh.startsWith("0")) {
                        String num = String.valueOf((Integer.valueOf(bh) + 1));

                        if (num.length() == 5) {
                            slbh = top + time + num;
                        } else {
                            slbh = top + time + "0" + num;
                        }
                    } else {
                        String num = String.valueOf((Integer.valueOf(bh) + 1));
                        slbh = top + time + num;
                    }
                } else {
                    slbh = top + time + "00001";
                }
            }
        }
        return slbh;
    }

    /**
     * 局长信箱
     * @return
     */
        public List<Tsjy> getjzxx(String guid,String status){
            List<Tsjy> t= new ArrayList<>();
            try {
                t = weixinQueryMapper.getJzxx(status, guid);
            }catch (Exception e){
                e.printStackTrace();
            }
            for(int i=0;i<t.size();i++){
                System.out.println(t.get(i).toString());
            }
            return  t;
        }
    /**
     * 局长信箱详情
     * @return
     */
    public Tsjy getjzxxxq(String guid,String xjno){

        return  weixinQueryMapper.getJzxxxq(guid,xjno);
    }
    /**
     * 保存投诉建议-局长信箱信息
     */
    public Result savetsjyjzxx(Tsjy tsjy) {
        Result result=new Result();
        try {
            weixinQueryMapper.savetsjyjzxx(tsjy);
            result.setSucc(true);
            result.setMsg("提交成功！您请登录网上办事大厅【个人中心】-【我的局长信箱】栏目中查看民警答复及历史记录。");
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setSucc(false);
            result.setMsg("操作失败！");
            return result;
        }
    }

    /**
     * 保存投诉建议-警风警纪监督员意见建议信息
     */
    public String savetsjyjfjj(Tsjy tsjy) {
        String guid = UUID.randomUUID().toString().replace("-","");
        tsjy.setGuid(guid);
        tsjy.setXjno(getSlbh(Constant.TSJY_JFJJ));
        try {
            weixinQueryMapper.savetsjyjzxx(tsjy);
            return guid;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存微信举报-线索举报信息
     */
    public String savewxjbxsjb(ComplaintReport complaintReport) {
        String guid =complaintReport.getGuid();
        if (Strings.isNullOrEmpty(complaintReport.getGuid())) {

            complaintReport.setGuid( UUID.randomUUID().toString().replace("-",""));
        }
//        complaintReport.setGuid(guid);
        complaintReport.setPt(getSlbh(Constant.WXJB_XSJB));
        try {
            weixinQueryMapper.savewxjbxsjb(complaintReport);
            return guid;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存微信举报-城区禁放烟花爆竹举报信息
     */
    public String savewxjbjfyhbz(ComplaintReport complaintReport) {
        String guid = UUID.randomUUID().toString().replace("-","");
        complaintReport.setGuid(guid);
        complaintReport.setPt(getSlbh(Constant.WXJB_CQJFYHBZ));
        try {
            weixinQueryMapper.savewxjbxsjb(complaintReport);
            return guid;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存微信举报-公交车抓小偷举报信息
     */
    public String savewxjbjgjczxt(ComplaintReport complaintReport) {
        String guid = UUID.randomUUID().toString().replace("-","");
        complaintReport.setGuid(guid);
        complaintReport.setPt(getSlbh(Constant.WXJB_GJCZXT));
        try {
            weixinQueryMapper.savewxjbxsjb(complaintReport);
            return guid;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 保存快撤理赔
     */
    public boolean savekclp(KclpInfo kclpInfo , List<KclpPhoto> kclpPhotoList) {
        try {

            weixinQueryMapper.savekclpInfo(kclpInfo);

            for (int i = 0; i < kclpPhotoList.size(); i++) {
                KclpPhoto kclpPhoto = kclpPhotoList.get(i);
                weixinQueryMapper.savekclpPhoto(kclpPhoto);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Map<String,String>> getCaseLibraryList(String keyWord) {
        return weixinQueryMapper.getCaseLibraryList(keyWord);
    }

    @Override
    public boolean bcclxx(String guid, String hyzk, String mz, String jg, String xl) {
//        try {
//            weixinQueryMapper.bcclxx(guid,hyzk,mz,jg,xl);
//            return true;
//        }catch (Exception e){
//            e.printStackTrace();
//            return  false;
//        }
        return true;
    }

    @Override
    public String getTime() {
        return weixinQueryMapper.getTime();
    }

    @Override
    public String saveProjectAttchmentsAtt(byte[] bytes) throws IOException {
//        BASE64Encoder encoder = new BASE64Encoder();
        // 通过base64来转化图片
//        String data = encoder.encode(bytes);
        ProjectAttchmentsAtt projectAttchmentsAtt = new ProjectAttchmentsAtt();
        projectAttchmentsAtt.setGuid(UUID.randomUUID().toString());
        projectAttchmentsAtt.setFileContent("");
        int rt = weixinQueryMapper.saveProjectAttchmentsAtt(projectAttchmentsAtt);
        if(rt > 0){
            return projectAttchmentsAtt.getGuid();
        }else {
            return null;
        }
    }

    @Override
    @Transactional
    public CaseLibrary loadHZMattersDetail(String caseGuid) {
        try {
            CaseLibrary caseLibrary = weixinQueryMapper.findHZCaseByGuid(caseGuid);

            String refguid = caseLibrary.getGuid();
            List<CaseMaterial> materialList = weixinQueryMapper.getCaseMaterilList(refguid);
            List<CaseBasiss> basisList = weixinQueryMapper.getCaseBasisList(refguid);

            if(caseLibrary.getIsPay().equals("1")){
                //收费事项，获取收费信息
                List<CasePay> casePay = weixinQueryMapper.findCasePay(refguid);
                caseLibrary.setCasePay(casePay);
            }

            caseLibrary.setMaterialList(materialList);
            caseLibrary.setBasisList(basisList);

            return caseLibrary;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private String doProjectApplyOrDraft(ProjectItem projectItem, CaseView caseView,WtMember members){
        String temp1 = "";
        if(StringUtils.isNotBlank(projectItem.getGuid())){
            //办件guid不为空 更新办件表 删除材料信息 邮寄信息 自定义表单信息
            ProjectItem tempProject = weixinQueryMapper.findProjectItem(projectItem.getGuid());
            BeanUtils.copyProperties(tempProject,projectItem);

            //办件提交类型为1：申报时，更新办件表状态为1：提交
            projectItem.setProjectStatus(1);
            projectItem.setProjectStatusCn("已提交");
            weixinQueryMapper.updateProjectStatus(projectItem);

            //删除邮寄信息
            weixinQueryMapper.delProjectNetEms(projectItem.getGuid());

        }else{
            //办件guid为空 新增办件信息
            //保存ASC_PROJECT
            projectItem.setProjectStatus(1);
            projectItem.setProjectStatusCn("已提交");
            temp1 = saveProjectItem(caseView,members,projectItem,projectItem.getPrjJzCode());
        }

        return temp1;
    }

    private String createMaxtOrderNo(String preNo, String sjmCode) {

        try {
            int count = weixinQueryMapper.countSequeceNumber(preNo);
            String sequeceNumber = String.format("%04d", count);
            String orderNo = preNo + sequeceNumber + sjmCode;

            weixinQueryMapper.saveSequeceNumber(orderNo, preNo);
            return orderNo;
        } catch (Exception e) {
            return "";
        }
    }

    private String createCheckCode(String SeqNO) {
        // 1  年月日 平台 模式  警种    13位
        try {
            int Key = 1;
            for (int i = 0; i < SeqNO.length(); i++) {
                Key += Integer.valueOf(SeqNO.charAt(i));
            }
            double r = Double.valueOf(SeqNO);
            double res = Key + r % Key;
            String result = String.valueOf((int)res);
            return result.substring(result.length() - 2, result.length());
        } catch (Exception e) {
            return "00";
        }
    }

    /**
     * 保存ASC_PROJECT
     *
     * @param caseView
     * @param members
     * @param projectItem
     * @param jzCode
     * @return
     */
    private String saveProjectItem(CaseView caseView,WtMember members,ProjectItem projectItem,String jzCode){
        projectItem.setGuid(UUID.randomUUID().toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String ys = sdf.format(new Date());
        String da = projectItem.getCaseDeptCode().substring(0,6);
        /**
         * 平台：01和91 表示办事大厅平台   02和92表示微服务接口
         * 模式：标识PC 01  表示微服务接口：02
         * 校验位：验证前面编号是否合法
         */
        String pt = "92";
        String ms = "02";
        jzCode = String.format("%02d", Integer.valueOf(jzCode));
        String preNo = ys+da+pt+ms+jzCode;
        String sjmCode = "";//随机码
        String orderNo = createMaxtOrderNo(preNo,sjmCode);
        String checkCode = createCheckCode(orderNo);
        orderNo = orderNo + checkCode;
        String orderNo1 = "W" + orderNo;
        //生成projectBillid
        projectItem.setProjectBillid(orderNo1);
        projectItem.setProjectType(caseView.getCaseType());
        projectItem.setIsPreprj(0);
        projectItem.setIsUnite(0);
        projectItem.setIsCharegeprj(caseView.getIsPay());
        projectItem.setStartDoDate(new Date());
        projectItem.setDueDays(caseView.getPromiseDays());
        projectItem.setUnitAttribute(null==members.getUserType()?1:Integer.valueOf(members.getUserType()));
        projectItem.setUnitName(members.getAliasName());
        projectItem.setUnitNumber(members.getUserCode());
        projectItem.setUnitAddress(members.getAddress());
        projectItem.setTelephone(members.getTelephone());
        projectItem.setUnitContactor(members.getLinkName());
        projectItem.setHandphone(members.getUserName());
        projectItem.setIsDeleted(0);
        projectItem.setNetProjectType(4);
        projectItem.setNetProjectCreatorGuid(members.getGuid());
        projectItem.setCreatorGuid(members.getGuid());
        projectItem.setCreatorDate(new Date());
        projectItem.setUpdateGuid(members.getGuid());
        projectItem.setUpdateDate(new Date());
        projectItem.setFlowsetGuid(caseView.getFlowCode());
        projectItem.setIsMydpj(0);
        //projectItem.setIsMailMertal(caseView.getIsEms());
        //projectItem.setUnionmainGuid();
        //projectItem.setProjectStatus(1);
        //projectItem.setProjectStatusCn("提交");
        projectItem.setCaseNo(caseView.getCaseNo());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(projectItem.getStartDoDate());
        calendar.add(calendar.DAY_OF_MONTH,Integer.valueOf(projectItem.getDueDays()));
        projectItem.setDueDate(calendar.getTime());
        String formId = weixinQueryMapper.findCaselibraryForm(caseView.getGuid());
        projectItem.setTemp5(formId);//TODO CASELIBRARY_FORM
        //projectItem.setTemp7();
        projectItem.setTemp8("1");
        projectItem.setIsCancelPrj(0);
        //projectItem.setPrjJzCode(Constant.POLICE_CATALOG_6);
        projectItem.setPrjCaseName(caseView.getCaseName());

        if(StringUtils.isBlank(projectItem.getFlowsetGuid())){
            String flowsetGuid = weixinQueryMapper.getDefaultFlowCode();
            projectItem.setFlowsetGuid(flowsetGuid);
        }

        weixinQueryMapper.saveProjectItem(projectItem);

        return orderNo;
    }

    @Override
    public ProjectItem doMattersApply(ProjectItem projectItem, JSONArray materials, List<ProjectNetEms> mailList) throws Exception {
        //获取事项详情信息
//        CaseLibrary caseLibrary = loadHZMattersDetail(projectItem.getProjectCaseGuid());
        CaseLibrary caseLibrary = loadHZMattersDetail(projectItem.getRefGuid());
        CaseView caseView = new CaseView();
        BeanUtils.copyProperties(caseLibrary,caseView);
        //获取用户信息
        WtMember members = wtMemberService.getWtMemberByUserGuid(projectItem.getCreatorGuid());
        members.setUserCode(DesAPPUtils.decrypt(members.getUserCode()));

        //判断必选材料附件是否上传
        List<ProjectAtt> projectAtts = new ArrayList<>();
        Map<String, String> isHave = new HashMap<>();
        for(int i = 0; i < materials.size(); i++){
            JSONObject jsonObject = materials.getJSONObject(i);
            ProjectAtt projectAtt = JSONObject.parseObject(jsonObject.toJSONString(),ProjectAtt.class);
            isHave.put(projectAtt.getMaterialGuid(),projectAtt.getIsHave());
            projectAtts.add(projectAtt);
        }
        List<CaseMaterial> list = caseView.getMaterialList();
        for(CaseMaterial caseMaterial : list){
            if(caseMaterial.getIsMust().equals("1") && !isHave.containsKey(caseMaterial.getGuid())){
                return null;
            }
        }

        //保存或更新ASC_PROJECT办件表，包括草稿、申报业务逻辑处理
        String temp1 = doProjectApplyOrDraft(projectItem,caseView,members);

        //保存材料信息 ASC_PROJECTMATERIAL  ASC_PROJECTATTACHMENTS  ASC_PROJECTATTACHMENTS_ATT
        saveProjectMaterials(projectAtts,caseView,projectItem,isHave);

        //邮寄信息
        saveProjectNetEmsList(mailList,projectItem,temp1);

        //电子监察
        saveMonitorApply(projectItem,caseView,members);

        return projectItem;
    }

    /**
     * 保存电子监察信息
     *
     * @param projectItem
     * @param caseView
     * @param members
     * @return
     */
    private int saveMonitorApply(ProjectItem projectItem,CaseView caseView,WtMember members){
        MonitorApply monitorApply = new MonitorApply();
        monitorApply.setDocNo(projectItem.getProjectBillid());
        monitorApply.setDocType(1);//
        monitorApply.setDataSouceType(0);
        monitorApply.setAppType(11);//
        monitorApply.setDocStatus(1);
        monitorApply.setDocStatusChageTime(new Date());
        monitorApply.setIsCancelPrj(0);
        //monitorApply.setCancelPrjDate();
        monitorApply.setPoliceCategory(caseView.getCasePoliceCategory());
        monitorApply.setCaseId(caseView.getRefguid());
        monitorApply.setCaseName(caseView.getCaseName());
        monitorApply.setAreaId(projectItem.getSjDeptCode());
        monitorApply.setAppDeptCode(projectItem.getCaseDeptCode());
        monitorApply.setAppDeptName(projectItem.getCaseDeptName());
        monitorApply.setAppTime(projectItem.getStartDoDate());
        monitorApply.setAppUserType(null==members.getUserType()?1:Integer.valueOf(members.getUserType()));
        monitorApply.setAppUserId(members.getGuid());
        monitorApply.setAppUserName(members.getUserName());
        monitorApply.setUserCode(members.getUserCode());
        monitorApply.setAppUserAddr(members.getAddress());
        monitorApply.setHandPhone(members.getUserName());
        monitorApply.setAppIpAddr("");
        monitorApply.setCreateTime(new Date());
        monitorApply.setExtendedTime(projectItem.getDueDate());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(projectItem.getStartDoDate());
        calendar.add(calendar.DAY_OF_MONTH,(Integer.valueOf(projectItem.getDueDays())-2));
        monitorApply.setWarningTime(calendar.getTime());
        return weixinQueryMapper.saveMonitorApply(monitorApply);
    }

    /**
     * 保存办件邮寄信息
     *
     * @param mailList
     * @param projectItem
     */
    private void saveProjectNetEmsList(List<ProjectNetEms> mailList,ProjectItem projectItem,String temp1){
        for (ProjectNetEms projectNetEms:mailList){
            projectNetEms.setProjectGuid(projectItem.getGuid());
            projectNetEms.setBjsbbh(projectItem.getProjectBillid());
            projectNetEms.setGuid(UUID.randomUUID().toString());
            projectNetEms.setStatus("0");
            projectNetEms.setZfzt("0");
            projectNetEms.setCreateTime(new Date());
            projectNetEms.setTemp1(temp1);
            projectNetEms.setTemp5("0");//写死0
            weixinQueryMapper.saveProjectNetEms(projectNetEms);
        }
    }

    /**
     * 保存材料信息
     *
     * @param projectAtts
     * @param caseView
     * @param projectItem
     * @param isHave
     */
    private void saveProjectMaterials(List<ProjectAtt> projectAtts,CaseView caseView,ProjectItem projectItem,Map<String, String> isHave){

        for(CaseMaterial caseMaterial : caseView.getMaterialList()){
            ProjectMaterials projectMaterials = new ProjectMaterials();
            projectMaterials.setLguid(UUID.randomUUID().toString());
            projectMaterials.setProjectGuid(projectItem.getGuid());
            projectMaterials.setProjectMaterialName(caseMaterial.getMaterial());
            projectMaterials.setIsNeed(caseMaterial.getIsMust());
            projectMaterials.setGetMethod(caseMaterial.getsType());
            projectMaterials.setMaterialGuid(caseMaterial.getGuid());
            projectMaterials.setSortId(caseMaterial.getOrderIndex());
            projectMaterials.setIsClass("0");//是否归类名 0不是 1是
            projectMaterials.setIsHave(isHave.get(caseMaterial.getGuid()));
            //保存ASC_PROJECTMATERIAL
            weixinQueryMapper.saveProjectMaterials(projectMaterials);

            for(ProjectAtt projectAtt : projectAtts){
                if(projectAtt.getMaterialGuid().equals(projectMaterials.getMaterialGuid())){
                    ProjectAttachments projectAttachments = new ProjectAttachments();
                    projectAttachments.setGuid(UUID.randomUUID().toString());
                    projectAttachments.setFloderguid(projectAtt.getAttGuid());
                    projectAttachments.setBizGuid(projectMaterials.getLguid());
                    projectAttachments.setAttachmentType("1");
                    String friendlyFileName = projectAtt.getFriendlyFileName();
                    String suffix = friendlyFileName.substring(friendlyFileName.lastIndexOf(".")+1);
                    projectAttachments.setFileName(projectAttachments.getGuid() + suffix);
                    projectAttachments.setContentType(suffix);
                    projectAttachments.setContentSize(projectAtt.getContentSize());
                    projectAttachments.setFriendlyFileName(friendlyFileName);
                    projectAttachments.setDateCreated(new Date());
                    projectAttachments.setPrjguid(projectItem.getGuid());
                    String time =getTime();
                    time.substring(0,5);
                    projectAttachments.setTemp2(time.substring(0,6)+"\\"+projectAtt.getAttGuid()+"_"+time.substring(0,6)+"."+suffix);
                    weixinQueryMapper.saveProjectAttachments(projectAttachments);
                }
            }
        }
    }

    @Override
    public Boolean doWorkFlow(ProjectItem projectItem) {
        Map<String,String> map = new HashMap<>();
        map.put("FlowCode",projectItem.getFlowsetGuid());
        map.put("ProjectGuid",projectItem.getGuid());
        map.put("CaseDeptID",projectItem.getCaseDeptCode());
        map.put("UserGuid",projectItem.getCreatorGuid());
        map.put("UserName",projectItem.getUnitName());
        String result = HttpClientUtil.doPostByMap(configInfo.getWorkFlowUrl(),map,"UTF-8");
        return Boolean.TRUE;


    }

    @Override
    @Transactional
    public CaseLibrary loadMattersDetail(String caseGuid) {
        try {
            CaseLibrary caseLibrary = weixinQueryMapper.findHZCaseByGuid(caseGuid);

            String refguid = caseLibrary.getGuid();
            List<CaseMaterial> materialList = weixinQueryMapper.getCaseMaterilList(refguid);
            List<CaseBasiss> basisList = weixinQueryMapper.getCaseBasisList(refguid);

            if(caseLibrary.getIsPay().equals("1")){
                //收费事项，获取收费信息
                List<CasePay> casePay = weixinQueryMapper.findCasePay(refguid);
                caseLibrary.setCasePay(casePay);
            }

            caseLibrary.setMaterialList(materialList);
            caseLibrary.setBasisList(basisList);

            return caseLibrary;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public SysOrgDept getSysOrgById(String orgid) {
        return weixinQueryMapper.getSysOrgById(orgid);
    }

    @Override
    public List<ProjectNetEms> getYjxxByPrjId(String projectGuid) {
        return weixinQueryMapper.getYjxxByPrjId(projectGuid);
    }

    @Override
    public WtMemberMange getWtMemberMange(String guid) {
        return this.weixinQueryMapper.getWtMemberMange(guid);
    }

    @Override
    public String getCaceLibraryTemp1(String caseNo, String orgid) {
        return weixinQueryMapper.getCaceLibraryTemp1(caseNo,orgid);
    }

    @Override
    public String getPascMembersMangeTemp3(String userGuid) {
        return weixinQueryMapper.getPascMembersMangeTemp3(userGuid);
    }

    @Override
    public List<Dictionary> selectCrtype(String code)throws IOException{

        String url = configInfo.getServiceInterfaceAddress() + "/base/key/"+code;
        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));
        List<Dictionary> listType= new ArrayList<>();
        listType  = JSONObject.parseArray(object.getString("data"),Dictionary.class);
        List<Dictionary> listTypeT= new ArrayList<>();
        for(int i=0;i<listType.size();i++){
          if(!"00".equals(listType.get(i).getVal())){
              listTypeT.add(listType.get(i));
          }
        }
        return listTypeT;

    }

    /**
     * 出入境办理进度
     * @param request
     * @return
     */
    @Override
    public Result getEntry(HttpServletRequest request){


        String id=request.getParameter("id");
        String code=request.getParameter("code");
        String validCode=request.getParameter("validCode");
        String genGuid=request.getParameter("genGuid");
        String url = configInfo.getServiceInterfaceAddress() + "/querys/entryExit/";
//        String url = "http://localhost:9005/querys/entryExit/";
        String res = "";
        try {
            res = HttpClientUtil.doPostString(url, new HashMap<String,String>(){
                {
                    put("id", id);
                    put("code", code);
                    put("validCode", validCode);
                    put("genGuid", genGuid);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject object=JSON.parseObject(res);
        Boolean b= (Boolean) object.get("succ");
        if(!b){
            return new Result(Result.FAILURE,object.getString("msg"));
        }
        if(null== object.get("data")){
            return new Result(Result.FAILURE,"无查询结果");
        }

        return new Result(Result.SUCC,object.getJSONObject("data"));

    }

    @Override
    public Result saveytwxjbxsjb(HttpServletRequest request)throws IOException{
        CptComplaintReportOut cptComplaintReportOut = new CptComplaintReportOut();
        if( null!=request.getParameter("cptComplaintReportAtts")){
            String str = request.getParameter("cptComplaintReportAtts");
            str.substring(0, str.lastIndexOf(","));
            String[] strArray = null;
            strArray = str.split(",");
            List<CptComplaintReportAtt> list = new ArrayList<>();
            for(int i=0;i<strArray.length;i++){
                String[] strTArray = null;
                strTArray = strArray[i].replace("{","").replace("}","").split(";");
                CptComplaintReportAtt cptComplaintReportAtt = new CptComplaintReportAtt();
                cptComplaintReportAtt.setUid(strTArray[0]);
                cptComplaintReportAtt.setGuid(strTArray[1]);
                cptComplaintReportAtt.setFsize(Long.parseLong(strTArray[2]));
                cptComplaintReportAtt.setFname(strTArray[3]);
                cptComplaintReportAtt.setAttachtype(Short.parseShort(strTArray[4]));
                list.add(cptComplaintReportAtt);
            }
            cptComplaintReportOut.setCptComplaintReportAtts(list);
        }

        cptComplaintReportOut.setCrtitle(request.getParameter("crtitle"));
        cptComplaintReportOut.setCrtype(request.getParameter("crtype"));
        cptComplaintReportOut.setCrcontent(request.getParameter("crcontent"));
        cptComplaintReportOut.setCurrentMemberMobile(request.getParameter("currentMemberMobile"));
        cptComplaintReportOut.setGuid(request.getParameter("guid"));
        cptComplaintReportOut.setUserguid(request.getParameter("userguid"));
        cptComplaintReportOut.setUsername(request.getParameter("username"));
        cptComplaintReportOut.setContanctperson(request.getParameter("contanctperson"));
        cptComplaintReportOut.setContanctphone(request.getParameter("contanctphone"));


        String url = configInfo.getServiceInterfaceAddress() + "/apphub/report";

        JSONObject object = JSON.parseObject(HttpClientUtil.doPostString(url,cptComplaintReportOut));
        System.out.println("data="+object.getJSONObject("data"));
        if(null!= object.getJSONObject("data")){
            return new Result(Result.SUCC,object.getJSONObject("data"));
        }

        return new Result(Result.FAILURE);


    }

}
